//
//  GrowManager.m
//  leo
//
//  Created by 常艳 on 15/12/10.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "GrowManager.h"
#import "Tooler.h"
#import "VoiceConverter.h"
@import AVFoundation;
@import AudioToolbox;
@implementation GrowManager
+(GrowManager *)sharedSingleton
{
    static GrowManager *growManager;
    @synchronized(self)
    {
        if(growManager==NULL)
            growManager=[[GrowManager alloc] init];
    }
    return growManager;
}
-(id)init
{
    
    self=[super init];
    self.theRequeseter=[[HttpRequester alloc] init];
    self.theDbHelper=[[DBHelper alloc] init];
    self.theManager=[[DataManager alloc] init];
    self.growDataManager=[[GrowDataManager alloc] init];
    return self;
}
-(void)dealloc
{
    self.theRequeseter=NULL;
    self.theDbHelper=NULL;
    self.theManager=NULL;
    self.growDataManager=NULL;
}
//获取系统任务
-(void)getPresetTasks:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,getPresetTasks enteres.",GrowManager_TAG);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,description);
        return;
    }
    if(callback==NULL)
    {
        NSLog(@"%@,getPresetTasks,parameter is illegal.",GrowManager_TAG);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getPresetTasks,user is null.",GrowManager_TAG);
        callback(FAIL,NULL,description);
        return;
    }
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getPresetTasks" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getPresetTasks,resdict is null",GrowManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getPresetTasks success.",GrowManager_TAG);
            NSArray *taskData=[resdict valueForKey:@"tasks"];
            if(taskData==NULL||[taskData count]==0)
            {
                NSLog(@"%@,getPresetTasks,taskData is null.",GrowManager_TAG);
                callback(SUCESS,NULL,NULL);
                return;
            }
            NSMutableArray *taskArray=[[NSMutableArray alloc] init];
            if(taskArray==NULL)
            {
                NSLog(@"%@,getPresetTasks,taskArray is null.",GrowDataManager_TAG);
                return;
            }
            for(int i=0;i<[taskData count];i++)
            {
                NSDictionary *taskInfo=[taskData objectAtIndex:i];
                if(taskInfo==NULL||[taskInfo count]==0)
                {
                    NSLog(@"%@,taskInfo is null.",GrowManager_TAG);
                    continue;
                }
                Task *task=[[Task alloc] init];
                if(task==NULL)
                {
                    continue;
                }
                task.taskId=[taskInfo valueForKey:@"id"];
                task.type=[[taskInfo valueForKey:@"type"] intValue];
                task.expireTs=[[taskInfo valueForKey:@"expireTs"] longValue];
                task.title=[taskInfo valueForKey:@"appTitle"];
                task.desc=[taskInfo valueForKey:@"appDesc"];
                task.empirical=[[taskInfo valueForKey:@"exp"] intValue];
                task.audioHash=[taskInfo valueForKey:@"audioHash"];
                task.downAudioUrl=[taskInfo valueForKey:@"aUrl"];
                task.duration=[[taskInfo valueForKey:@"duration"] intValue];
                task.photoHash=[taskInfo valueForKey:@"photoHash"];
                task.downPicUrl=[taskInfo valueForKey:@"pUrl"];
                task.update_time=[taskInfo valueForKey:@"updateTime"];
                task.createTime=[taskInfo valueForKey:@"createTime"];
                task.isActive=[[taskInfo valueForKey:@"active"] intValue];
                
                //UI更改
                task.tips = [taskInfo valueForKey:@"tips"];
                [taskArray addObject:task];
                task=NULL;
            }
            if([taskArray count]>0)
            {
                [self.growDataManager addsysTasks:taskArray];
            }
            [self downSysTaskFiles:taskArray];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getPresetTasks,fail,error code is %@",GrowManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];

}
-(void)downSysTaskFiles:(NSArray *)taskArray
{
    if(taskArray==NULL||[taskArray count]==0)
        return;
    for(int i=0;i<[taskArray count];i++)
    {
        Task *task=[taskArray objectAtIndex:i];
        if(task==NULL)
            continue;
        if(task.downPicUrl!=NULL)
            [self getTaskPic:task.downPicUrl taskId:task.taskId type:SYSTASK];
        if(task.downAudioUrl!=NULL)
            //[self getTaskAudio:task.downAudioUrl randomCode:task.taskId type:SYSTASK audioHash:task.audioHash theId:NULL];
            [self getTaskAudioByHash:task.audioHash randomCode:task.taskId type:SYSTASK theId:NULL];
        task=NULL;
    }
}
-(void)getTaskPic:(NSString *)url taskId:(NSString *)taskId type:(TaskFileType)type
{
    NSLog(@"%@,getTaskPic,url is %@.",GrowManager_TAG,url);
    if(url==NULL||taskId==NULL)
    {
        NSLog(@"%@,getTaskPic,parameter is illegal.",GrowDataManager_TAG);
        return;
    }
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue==NULL)
    {
        NSLog(@"%@,getTaskPic,queue is null",DATAMANAGER_TAG);
        return;
    }
    dispatch_async(queue, ^{
        //下载头像
        NSString *directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/grow"];
        if(![Tooler isDirectoryExist:directoryPath])
        {
            return;
        }
        NSString *fileName=[NSString stringWithFormat:@"/image%@.png",[Tooler getTS]];
        NSString *filePath=[directoryPath stringByAppendingString:fileName];
        BOOL is_downLoad=[self.theRequeseter downLoadFile:url filePath:filePath];
        if(is_downLoad)
        {
             //更新图片路径
            NSString *picUrl=[NSString stringWithFormat:@"/grow%@",fileName];
            if(type==SYSTASK)
                [self.growDataManager updateSysTaskPic:picUrl taskId:taskId];
            else if(type==HISTORYTASK)
                [self.growDataManager updateHistoryTaskPic:picUrl taskId:taskId];
            else if(type==PUSHTASK)
                [self.growDataManager updatePushTaskPic:picUrl randomCode:taskId];
                
        }
    });
}
-(void)getTaskAudioByHash:(NSString *)audioHash randomCode:(NSString *)randomCode type:(TaskFileType)type theId:(NSString *)theId
{
    NSLog(@"%@,getTaskAudioByHash entered,audioHash is %@.",GrowManager_TAG,GrowManager_TAG);
    if(audioHash==NULL||[audioHash isEqualToString:@"(null)"]||[audioHash length]==0)
    {
        NSLog(@"%@,getTaskAudioByHash,audioHash is illegal.",GrowManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL||user.uid==NULL)
    {
        NSLog(@"%@,getTaskAudioByHash,user is null",GrowManager_TAG);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSString *data=[NSString stringWithFormat:@"{\"fileHash\":\"%@\"}",audioHash];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:uid forKey:@"uid"];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:data forKey:@"data"];
    [param setValue:@"UserApiImpl.getFileUrl" forKey:@"method"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getTaskAudioByHash,resdict is null",GrowManager_TAG);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue==NULL)
            {
                NSLog(@"%@,getTaskAudioByHash,queue is null",DATAMANAGER_TAG);
                return;
            }
            dispatch_async(queue, ^{
                
                
                NSString *url=[resdict valueForKey:@"url"];
                if(url==NULL||[url length]<=0)
                {
                    NSLog(@"%@,getTaskAudioByHash,url is null.",DATAMANAGER_TAG);
                    return;
                }
                NSString *directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/grow"];
                if(![Tooler isDirectoryExist:directoryPath])
                {
                    return;
                }
                NSString *ts=[Tooler getTS];
                NSString *fileName=[NSString stringWithFormat:@"/audio%@.amr",ts];
                NSString *wavName=[NSString stringWithFormat:@"/audio%@.wav",ts];
                NSString *filePath=[directoryPath stringByAppendingString:fileName];
                NSString *wavPath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",wavName]];
                BOOL is_downLoad=[self.theRequeseter downLoadFile:url filePath:filePath];
                if(is_downLoad)
                {
                    //把amr转换成wav的
                    if(![VoiceConverter ConvertAmrToWav:filePath wavSavePath:wavPath])
                        return;
                    //更新图片路径
                    NSString *audioUrl=[NSString stringWithFormat:@"/grow%@",wavName];
                    if(type==SYSTASK)
                        [self.growDataManager updateSysTaskAudio:audioUrl taskId:randomCode];
                    else if(type==HISTORYTASK)
                    {
                        [self.growDataManager updateHistoryTaskAudio:audioUrl randomCode:randomCode targetUid:theId audioHash:audioHash];
                        [[NSNotificationCenter defaultCenter] postNotificationName:RECEIVEDPUSHTASK object:nil  userInfo:nil];
                    }
                    else if(type==PUSHTASK)
                    {
                        [self.growDataManager updatePushTaskAudio:audioUrl randomCode:randomCode targetUid:theId audioHash:audioHash];
                        [[NSNotificationCenter defaultCenter] postNotificationName:RECEIVEDPUSHTASK object:nil  userInfo:nil];
                    }
                }

            });
        }
    }];

}
-(void)getTaskAudio:(NSString *)url randomCode:(NSString *)randomCode type:(TaskFileType)type audioHash:(NSString *)audioHash theId:(NSString *)theId
{
    NSLog(@"%@,getTaskAudio,url is %@.",GrowManager_TAG,url);
    if(url==NULL||randomCode==NULL)
    {
        NSLog(@"%@,getTaskAudio,parameter is illegal.",GrowDataManager_TAG);
        return;
    }
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue==NULL)
    {
        NSLog(@"%@,getTaskAudio,queue is null",DATAMANAGER_TAG);
        return;
    }
    dispatch_async(queue, ^{
        NSString *directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/grow"];
        if(![Tooler isDirectoryExist:directoryPath])
        {
            return;
        }
        NSString *ts=[Tooler getTS];
        NSString *fileName=[NSString stringWithFormat:@"/audio%@.amr",ts];
        NSString *wavName=[NSString stringWithFormat:@"/audio%@.wav",ts];
        NSString *filePath=[directoryPath stringByAppendingString:fileName];
        NSString *wavPath=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",wavName]];
        BOOL is_downLoad=[self.theRequeseter downLoadFile:url filePath:filePath];
        if(is_downLoad)
        {
            //把amr转换成wav的
            if(![VoiceConverter ConvertAmrToWav:filePath wavSavePath:wavPath])
                return;
            //更新图片路径
            NSString *audioUrl=[NSString stringWithFormat:@"/grow%@",wavName];
            if(type==SYSTASK)
                [self.growDataManager updateSysTaskAudio:audioUrl taskId:randomCode];
            else if(type==HISTORYTASK)
            {
                [self.growDataManager updateHistoryTaskAudio:audioUrl randomCode:randomCode targetUid:theId audioHash:audioHash];
                [[NSNotificationCenter defaultCenter] postNotificationName:RECEIVEDPUSHTASK object:nil  userInfo:nil];
            }
            else if(type==PUSHTASK)
            {
                [self.growDataManager updatePushTaskAudio:audioUrl randomCode:randomCode targetUid:theId audioHash:audioHash];
                [[NSNotificationCenter defaultCenter] postNotificationName:RECEIVEDPUSHTASK object:nil  userInfo:nil];
            }
        }
    });
}

//布置任务
-(void)assignTask:(Task *)task completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,assignTask entered.",GrowManager_TAG);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,description);
        return;
    }
    if(task==NULL||task.taskId==NULL||!([task.taskId intValue]>0))
    {
        NSLog(@"%@,assignTask,parameter is illegal.",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,assignTask,user is null.",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"task\":{\"id\":%@}}",task.targetUid,task.taskId];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.assignTask" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,assignTask,resdict is null",GrowManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,assignTask success.",GrowManager_TAG);
            NSString *randomCode=[resdict valueForKey:@"randomCode"];
            task.randomCode=randomCode;
            task.update_time=[Tooler getTS];
            [self.growDataManager setTask:task];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,assignTask,fail,error code is %@",GrowManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
    

}
//完成任务
-(void)finishTask:(Task *)task   completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,finishTask enter.",GrowManager_TAG);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,NULL);
        return;
    }
    if(task==NULL||task.randomCode==NULL)
    {
        NSLog(@"%@,finishTask,parameter is null.",GrowManager_TAG);
        callback(FAIL,NULL,description);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,finishTask,user is null.",DATAMANAGER_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"targetUid\":%@,\"randomCode\":\"%@\",\"task\":{\"duration\":%d}}",task.targetUid,task.randomCode,task.duration];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.finishTask" forKey:@"method"];
    [param setValue:data forKey:@"data"];
    NSString *urlStr=[NSString stringWithFormat:@"%@://%@/v1/api/upload.json",protol,hostName];
    NSString *fileUrl=NULL;
    if(task.picUrl!=NULL&&![fileUrl isEqualToString:@"(null)"]&&![task.picUrl isEqualToString:@""])
    {
        fileUrl=task.picUrl;
    }
    if(task.audioUrl!=NULL&&![task.audioUrl isEqualToString:@"(null)"]&&![task.audioUrl isEqualToString:@""])
    {
        fileUrl=task.saveAmrUrl;
    }
   [self.theRequeseter postFile:urlStr fileName:NULL filePath:fileUrl param:param completion:^(NSDictionary *resdict) {
       if(resdict==NULL||[resdict count]==0)
       {
           NSLog(@"%@,finishTask,resdict is null",GrowManager_TAG);
           callback(NODATA,NULL,NULL);
           return;
       }
       NSString *ret=[resdict valueForKey:@"success"];
       if(ret!=NULL&&[ret intValue]==1)
       {
           NSLog(@"%@,finishTask success.",GrowManager_TAG);
           //更改任务状态
           task.status=DONE;
           [self.growDataManager finishTask:task];
           callback(SUCESS,NULL,NULL);
       }
       else
       {
           NSString *errorCode=[resdict valueForKey:@"errorCode"];
           NSLog(@"%@,finishTask,fail,error code is %@",GrowManager_TAG,errorCode);
           callback(FAIL,NULL,[self getErrorInfo:errorCode]);
       }

   }];
}
//确认完成任务
-(void)confirmTask:(Task *)task  result:(BOOL)result completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,confirmTask entered.",GrowManager_TAG);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,description);
        return;
    }
    if(task==NULL||task.randomCode==NULL)
    {
        NSLog(@"%@,confirmTask,parameter is illegal.",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,confirmTask,user is null.",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *data=[NSString stringWithFormat:@"{\"randomCode\":\"%@\",\"result\":%d}",task.randomCode,result];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.confirmTask" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,confirmTask,resdict is null",GrowManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,confirmTask success.",GrowManager_TAG);
            //更改任务状态
            if(result)
            {
                task.status=DONE;
            }
            else
            {
                task.status=UNDO;
            }
            [self.growDataManager confirmTask:task];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,confirmTask,fail,error code is %@",GrowManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
//获取历史任务
-(void)getHistoryTask:(NSString *)deviceUid randomCode:(NSString *)randomCode completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,getHistoryTask entered.",GrowManager_TAG);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,description);
        return;
    }
    if(deviceUid==NULL||!([deviceUid intValue]>0))
    {
        NSLog(@"%@,getHistoryTask,parameter is illegal.",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getHistoryTask,user is null.",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *ts=[self.growDataManager getMaxTaskTime:user.uid deviceUid:deviceUid];
    NSString *data=NULL;
    if(randomCode==NULL||[randomCode isEqualToString:@"(null)"]||[randomCode isEqualToString:@""])
    {
        data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"ts\":%@,\"task\":{\"status\":null}}",deviceUid,ts];
    }
    else
    {
        //data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"ts\":%@,\"task\":{\"status\":null,\"randomCode\":\"%@\"}}",deviceUid,ts,randomCode];
        data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"task\":{\"status\":null,\"randomCode\":\"%@\"}}",deviceUid,randomCode];
    }

    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getHistoryTasks" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getHistoryTask,resdict is null",GrowManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getHistoryTask success.",GrowManager_TAG);
            //解析任务数据
            NSArray *taskData=[resdict valueForKey:@"tasks"];
            if(taskData==NULL||[taskData count]==0)
            {
                callback(SUCESS,NULL,NULL);
                return;
            }
            NSString *updateTime=[resdict valueForKey:@"ts"];
            NSMutableArray *taskArray=[[NSMutableArray alloc] init];
            for(int i=0;i<[taskData count];i++)
            {
                NSDictionary *taskInfo=[taskData objectAtIndex:i];
                if(taskInfo==NULL)
                    continue;
                Task *task=[[Task alloc] init];
                task.ownerUid=[taskInfo valueForKey:@"uid"];
                task.targetUid=[taskInfo valueForKey:@"deviceUid"];
                task.taskId=[taskInfo valueForKey:@"id"];
                task.type=[[taskInfo valueForKey:@"type"] intValue];
                task.status=[[taskInfo valueForKey:@"status"] intValue];
                task.expireTs=[[taskInfo valueForKey:@"expireTime"] longValue];
                task.createTime=[taskInfo valueForKey:@"createTime"];
                task.pushTime=[taskInfo valueForKey:@"pushTime"];
                task.finishTime=[taskInfo valueForKey:@"finishTime"];
                task.title=[taskInfo valueForKey:@"appTitle"];
                task.desc=[taskInfo valueForKey:@"appDesc"];
                task.empirical=[[taskInfo valueForKey:@"exp"] intValue];
                task.audioHash=[taskInfo valueForKey:@"audioHash"];
                task.downAudioUrl=[taskInfo valueForKey:@"aUrl"];
                task.duration=[[taskInfo valueForKey:@"duration"] intValue];
                task.photoHash=[taskInfo valueForKey:@"photoHash"];
                task.downPicUrl=[taskInfo valueForKey:@"pUrl"];
                task.update_time=updateTime;
                task.action=PROMPT;
                task.randomCode=[taskInfo valueForKey:@"randomCode"];
                NSString *executorStr=[taskInfo valueForKey:@"executorType"];
                if(executorStr!=NULL)
                {
                    int executorType=[executorStr intValue];
                    if(executorType==2)//1watch 2phone
                    {
                        task.action=RECORD;
                    }
                    else if(executorType==1)
                    {
                        NSString *responseStr=[taskInfo valueForKey:@"responseType"];
                        if(responseStr!=NULL)
                        {
                            int responseType=[responseStr intValue];
                            if(responseType==1)//1不需上传数据  2需上传数据
                            {
                                task.action=CONFIRM;
                            }
                            else if(responseType==2)
                            {
                                task.action=PROMPT;
                            }
                        }
                    }
                }
                [taskArray addObject:task];
                task=NULL;
            }
            if([taskArray count]>0)
            {
                [self.growDataManager addHistoryTasks:taskArray];
            }
            [self downHistoryTaskFiles:taskArray];
            callback(SUCESS,NULL,NULL);
            if(randomCode!=NULL)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:RECEIVEDPUSHTASK object:nil  userInfo:nil];
            }
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getHistoryTask,fail,error code is %@",GrowManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
-(void)downHistoryTaskFiles:(NSArray *)taskArray
{
    if(taskArray==NULL||[taskArray count]==0)
        return;
    for(int i=0;i<[taskArray count];i++)
    {
        Task *task=[taskArray objectAtIndex:i];
        if(task==NULL)
            continue;
        if(task.downPicUrl!=NULL)
            [self getTaskPic:task.downPicUrl taskId:task.taskId type:HISTORYTASK];
        NSString *oldHash=[self.growDataManager getTaskAudioHash:task.randomCode targetUid:task.targetUid];
        if(oldHash==NULL||[oldHash isEqualToString:@"(null)"]||[oldHash isEqualToString:@""]||![oldHash isEqualToString:task.audioHash])
        {
            if(task.downAudioUrl!=NULL&&![task.downAudioUrl isEqualToString:@"(null)"]&&![task.downAudioUrl isEqualToString:@""])
                //[self getTaskAudio:task.downAudioUrl randomCode:task.randomCode type:HISTORYTASK audioHash:task.audioHash theId:task.targetUid];
                  [self getTaskAudioByHash:task.audioHash randomCode:task.randomCode type:HISTORYTASK theId:task.targetUid];
            else
            {
                [self getTaskAudioByHash:task.audioHash randomCode:task.randomCode type:HISTORYTASK theId:task.targetUid];
            }
        }

    }
}

//获取手表经验等级策略
-(void)getExpPolicy:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,getExpPolicy entered.",GrowManager_TAG);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,description);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getExpPolicy,user is null.",GrowManager_TAG);
         callback(FAIL,NULL,NULL);
        return;
    }
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getExpPolicy" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getExpPolicy,resdict is null",GrowManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getExpPolicy success.",GrowManager_TAG);
            //更改任务状态
            NSArray *policyData=[resdict valueForKey:@"expPolicies"];
            if(policyData==NULL||[policyData count]==0)
            {
                NSLog(@"%@,getExpPolicy,policyArray is null.",GrowDataManager_TAG);
                callback(SUCESS,NULL,NULL);
                return;
            }
            NSMutableArray *policyArray=[[NSMutableArray alloc] init];
            if(policyArray==NULL)
                return;
            for(int i=0;i<[policyData count];i++)
            {
                NSDictionary *policyInfo=[policyData objectAtIndex:i];
                if(policyInfo==NULL||[policyInfo count]==0)
                    continue;
                ExpPolicy *policy=[[ExpPolicy alloc] init];
                policy.level=[[policyInfo valueForKey:@"level"] intValue];
                policy.exp=[[policyInfo valueForKey:@"exp"] intValue];
                [policyArray addObject:policy];
                policy=NULL;
            }
            [self.growDataManager addPolicies:policyArray];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getExpPolicy,fail,error code is %@",GrowManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    } ];
}
//获取手表成长值
-(void)getGrowthData:(NSString *)deviceUid completion:(void (^)(SyncResult result,NSDictionary *retValue,NSString * description))callback
{
    NSLog(@"%@,getGrowthData entered.",GrowManager_TAG);
    NSString *description=NULL;
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            description=NO_NET_WORK_INFO;
        }
        callback(FAIL,NULL,description);
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getGrowthData,user is null.",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *ts=[Tooler getTS];
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":%@,\"ts\":%@}",deviceUid,ts];
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    [param setValue:user.accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getGrowthData" forKey:@"method"];
    [param setValue:user.uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getExpPolicy,resdict is null",GrowManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getExpPolicy success.",GrowManager_TAG);
            //更改任务状态
            NSDictionary *growthData=[resdict valueForKey:@"growthData"];
            if(growthData==NULL||[growthData count]==0)
            {
                callback(SUCESS,NULL,NULL);
                return;
            }
            Growth *growth=[[Growth alloc] init];
            growth.semp=[[growthData valueForKey:@"1"] intValue];
            growth.emp=[[growthData valueForKey:@"2"] intValue];
            growth.step=[[growthData valueForKey:@"3"] intValue];
            growth.blueNum=[[growthData valueForKey:@"4"] intValue];
            growth.chatNum=[[growthData valueForKey:@"5"] intValue];
            growth.callNum=[[growthData valueForKey:@"6"] intValue];
            growth.taskScore=[[growthData valueForKey:@"7"] intValue];
            
            ///////////////UI更改
            growth.continousDays = [[growthData valueForKey:@"8"] intValue];
            growth.createTime=[Tooler getTS];
            [self.growDataManager addGrowth:growth deviceUid:deviceUid];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getExpPolicy,fail,error code is %@",GrowManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }

    }];
}
-(NSString *)getErrorInfo:(NSString *)errorCode
{
    NSLog(@"%@,getErrorInfo enter. error code is %@",GrowManager_TAG,errorCode);
    if(errorCode==NULL||[errorCode intValue]<0)
    {
        NSLog(@"%@,getErrorInfo , error code is illegal",GrowManager_TAG);
        return NULL;
    }
    NSString *description=NULL;
    switch ([errorCode intValue]) {
        case USER_UNEXIST: description=USER_UNEXIST_INFO;break;
        case DEVICE_ID_ILLEGAL: description=DEVICE_ID_ILLEGAL_INFO;break;
        case USER_ID_ILLEGAL: description=USER_ID_ILLEGAL_INFO;break;
        case USER_PERMISSION_NOT_ALLOWED: description=USER_PERMISSION_NOT_ALLOWED_INFO;break;
        case USER_DEVICE_NOT_BOUND: description=USER_DEVICE_NOT_BOUND_INFO;break;
        case USER_REQUEST_ILLEGAL: description=USER_REQUEST_ILLEGAL_INFO;break;
        case USER_BIND_DEVICE_NULL: description=USER_BIND_DEVICE_NULL_INFO;break;
        case SMSCODE_VERIFY_FAILED:description=SMSCODE_VERIFY_FAILED_INFO;break;
        case USER_ALREADY_EXIST:description=USER_ALREADY_EXIST_INFO;break;
        case USER_ACCESS_TOKEN_EXPIRED:description=USER_ACCESS_TOKEN_EXPIRED_INFO;break;
        case USER_PWD_NOT_MATCH_USER:description=USER_PWD_NOT_MATCH_USER_INFO;break;
        case USER_LOGINED_ON_OTHER_DEVICE:description=USER_LOGINED_ON_OTHER_DEVICE_INFO;break;
        case USER_VERIFY_CODE_ILLEGAL:description=USER_VERIFY_CODE_ILLEGAL_INFO;break;
        case USER_UPDATE_PWD_FAILURE:description=USER_UPDATE_PWD_FAILURE_INFO;break;
        case USER_BIND_REQUEST_REJECTED:description=USER_BIND_REQUEST_REJECTED_INFO;break;
        case USER_PHONENUM_NONEXIST:description=USER_PHONENUM_NONEXIST_INFO;break;
        case USER_PHONENUM_ALREADY_REGISTER:description=USER_PHONENUM_ALREADY_REGISTER_INFO;break;
        case USER_FULLNAME_NONEXIST:description=USER_FULLNAME_NONEXIST_INFO;break;
        case USER_ACCOUNT_ALREADYEXIST:description=USER_ACCOUNT_ALREADYEXIST_INFO;break;
        case USER_GEOFENCE_IS_NULL:description=USER_GEOFENCE_IS_NULL_INFO;break;
        case USER_GEOFENCE_NON_EXIST:description=USER_GEOFENCE_NON_EXIST_INFO;break;
        case USER_GEOFENCE_ALREADY_DELETED:description=USER_GEOFENCE_ALREADY_DELETED_INFO;break;
        case USER_CONTACT_ALREADY_EXIST:description=USER_CONTACT_ALREADY_EXIST_INFO;break;
        case USER_CONTACT_NONEXIST:description=USER_CONTACT_NONEXIST_INFO;break;
        case USER_CONTACT_ALREADY_DELETED:description=USER_CONTACT_ALREADY_DELETED_INFO;break;
        case USER_REMINDER_ALREADY_EXIST:description=USER_REMINDER_ALREADY_EXIST_INFO;break;
        case USER_REMINDER_NONEXIST:description=USER_REMINDER_NONEXIST_INFO;break;
        case USER_REMINDER_ALREADY_DELETED:description=USER_REMINDER_ALREADY_DELETED_INFO;break;
        case USER_SILENTPERIOD_ALREADY_EXIST:description=USER_SILENTPERIOD_ALREADY_EXIST_INFO;break;
        case USER_SILENTPERIOD_NONEXIST:description=USER_SILENTPERIOD_NONEXIST_INFO;break;
        case USER_SILENTPERIOD_ALREADY_DELETED:description=USER_SILENTPERIOD_ALREADY_DELETED_INFO;break;
        case DEVICE_ALREADY_BOUND:description=DEVICE_ALREADY_BOUND_INFO;break;
        case SMS_SEND_FAILURE:description=SMS_SEND_FAILURE_INFO;break;
        case SMS_COUNT_REACH_UPPER_LIMIT:description=SMS_COUNT_REACH_UPPER_LIMIT_INFO;break;
        case SMS_VERIFY_FAILURE:description=SMS_VERIFY_FAILURE_INFO;break;
        case SMS_FREQUENCY_TOO_FAST:description=SMS_FREQUENCY_TOO_FAST_INFO;break;
        case SYSTEM_INNER_ERROR:description=SYSTEM_INNER_ERROR_INFO;break;
        case API_INVOCATION_FAILED:description=API_INVOCATION_FAILED_INFO;break;
        case GROUP_USER_NOT_IN_ONE_GROUP:description=GROUP_USER_NOT_IN_ONE_GROUP_INFO;break;
        case DEVICE_VERSION_IS_NEWEST:description=DEVICE_VERSION_IS_NEWEST_INFO;break;
        case APP_VERSION_IS_NEWEST:description=APP_VERSION_IS_NEWEST_INFO;break;
        case API_REFRESHTOKEN_INVALID:description=API_REFRESHTOKEN_INVALID_INFO;break;   
        default:
            description=[NSString stringWithFormat:@"unknown error:%@",errorCode];
            break;
    }
    return description;
}


-(SyncResult)checkValid
{
    
    //判断当前网络状况
    if([Tooler checkNetworkState]==3)
    {
        return NO_NET_WORK;
    }
    if(self.theRequeseter==NULL)
    {
        NSLog(@"%@,checkValid,theRequeseter is null",GrowManager_TAG);
        return ERROR;
    }
    if(self.theDbHelper==NULL)
    {
        NSLog(@"%@,checkValid,theDbHelper is null",GrowManager_TAG);
        return ERROR;
    }
    
    return SUCESS;
}

-(void)getWatchTheme:(void (^)(SyncResult result,NSDictionary *retValue,NSString *description))callback deviceUid:(NSString *)deviceUid
{
    NSLog(@"%@,getWatchTheme entered.",GrowManager_TAG);
    if(callback==NULL||deviceUid==NULL)
    {
        NSLog(@"%@,getWatchTheme,callback is null",GrowManager_TAG);
        return;
    }
    SyncResult valid=[self checkValid];
    if(valid!=SUCESS)
    {
        if(valid==NO_NET_WORK)
        {
            callback(FAIL,NULL,NO_NET_WORK_INFO);
        }
        else
        {
            callback(FAIL,NULL,NULL);
        }
        return;
    }
    NSString *urtStr=[NSString stringWithFormat:@"%@://%@/v1/api/call.json",protol,hostName];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,getWatchTheme,user is null",GrowManager_TAG);
        callback(FAIL,NULL,NULL);
        return;
    }
    NSString *uid=user.uid;
    NSString *accessToken=user.accessToken;
    NSMutableDictionary *param=[[NSMutableDictionary alloc] init];
    NSString *data=[NSString stringWithFormat:@"{\"deviceUid\":\"%@\"}",deviceUid];
    [param setValue:accessToken forKey:@"atoken"];
    [param setValue:@"UserApiImpl.getWatchTheme" forKey:@"method"];
    [param setValue:uid forKey:@"uid"];
    [param setValue:data forKey:@"data"];
    [self.theRequeseter asyncPost:urtStr parameters:param completion:^(NSDictionary *resdict) {
        if(resdict==NULL||[resdict count]==0)
        {
            NSLog(@"%@,getWatchTheme,resdict is null",GrowManager_TAG);
            callback(NODATA,NULL,NULL);
            return;
        }
        NSString *ret=[resdict valueForKey:@"success"];
        if(ret!=NULL&&[ret intValue]==1)
        {
            NSLog(@"%@,getWatchTheme success.",GrowManager_TAG);
            
            NSDictionary *themeInfo=[resdict valueForKey:@"theme"];
            if(themeInfo==NULL||[themeInfo count]==0)
            {
                callback(FAIL,NULL,NULL);
                return;
            }
            int themeId=[[themeInfo valueForKey:@"themeId"] intValue];
            int themeLevel=[[themeInfo valueForKey:@"wpLevel"] intValue];
            [self.growDataManager setWatchTheme:deviceUid themeId:themeId themeLevel:themeLevel];
            callback(SUCESS,NULL,NULL);
        }
        else
        {
            NSString *errorCode=[resdict valueForKey:@"errorCode"];
            NSLog(@"%@,getWatchTheme,fail,error code is %@",GrowManager_TAG,errorCode);
            callback(FAIL,NULL,[self getErrorInfo:errorCode]);
        }
        
    }];
    
}

@end
